package com.mzy.tomcat.utils;

import com.mzy.tomcat.MzyTomcatV3;
import com.mzy.tomcat.annotation.WebServlet;
import com.mzy.tomcat.servlet.MzyHttpServlet;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ScanAnnotation {

    public static void initAnnotation() throws Exception {
        // 获取类路径
        URL resource = ClassLoader.getSystemClassLoader().getResource("");
        String path = resource.getPath();

        // 获取所有类的类路径
        List<String> classFileList = new ArrayList<>();
        FileUtils.getClassFilePath(path, classFileList);

        // 扫描classes路径下所有的类
        // 将带有@WebServlet注解的类 注册到 servletUrlMapping 和 servletClassMapping 容器中
        for (String classFile : classFileList) {
            Class<?> clazz = Class.forName(classFile);
            WebServlet annotation = clazz.getAnnotation(WebServlet.class);
            if(annotation != null) {
                String name = clazz.getName();
                String[] urlPatterns = annotation.value();
                for (String urlPattern : urlPatterns) {
                    MzyTomcatV3.servletUrlMapping.put(urlPattern, name);
                    MzyTomcatV3.servletClassMapping.put(name, (MzyHttpServlet) clazz.newInstance());
                }
            }
        }


    }
}
